package packet

import (
	"encoding/binary"
	"time"
)

// LinkMonitorPacket represents a link monitoring packet
type LinkMonitorPacket struct {
	Header      *Header
	CurrentTime uint32 // 当前时刻，相对于北京时当日的积秒，量化单位为0.1ms
}

// NewLinkMonitorPacket creates a new link monitoring packet
func NewLinkMonitorPacket(sourceID, destID uint32) *LinkMonitorPacket {
	// Create target code bytes for link monitor (0xFFFFF0)
	targetCode := []byte{0xF0, 0xFF, 0xFF} // Stored in little-endian format

	// Calculate current time in 0.1ms units since midnight
	now := time.Now()
	midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
	milliseconds := uint32(now.Sub(midnight).Milliseconds())
	tenthsOfMilliseconds := milliseconds * 10 // Convert to 0.1ms units

	// Create header
	header := &Header{
		TargetCode:     targetCode,
		SourceID:       sourceID,
		DestinationID:  destID,
		DataFlag:       FlagLinkMonitor,
		SequenceNumber: 0, // Should be managed by the sender
		Reserved:       0,
		DataLength:     4, // Fixed at 4 bytes for link monitor
	}

	// Calculate send date and time
	header.calculateDateTime()

	return &LinkMonitorPacket{
		Header:      header,
		CurrentTime: tenthsOfMilliseconds,
	}
}

// Bytes converts the link monitor packet to a byte slice
func (p *LinkMonitorPacket) Bytes() []byte {
	headerBytes := p.Header.Bytes()
	dataBytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(dataBytes, p.CurrentTime)

	return append(headerBytes, dataBytes...)
}

// ParseLinkMonitorPacket parses a byte slice into a link monitor packet
func ParseLinkMonitorPacket(data []byte) (*LinkMonitorPacket, error) {
	if len(data) < HeaderLength+4 {
		return nil, ErrInvalidDataLength
	}

	header, err := Parse(data[:HeaderLength])
	if err != nil {
		return nil, err
	}

	currentTime := binary.LittleEndian.Uint32(data[HeaderLength : HeaderLength+4])

	return &LinkMonitorPacket{
		Header:      header,
		CurrentTime: currentTime,
	}, nil
}
